<template>
  <div class="pt-2">
    <el-card shadow="never" header-class="projecHead" body-class="projectCont">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <div class="flex items-center justify-between text-[12px] w-100%">
            <div class="text-[16px] pl-3 text-[#333] font-bold">预览区</div>
            <div class="flex items-center val" style="flex-direction: column">
              <div class="pr-[10px]">
                预计生成<span class="font-bold">{{ advCount }}</span
                >个广告
              </div>
              <div class="pt-[10px]">
                <el-button plain type="primary" v-hasPermi="['oce:templateTask:add']" @click="handlePreviewSubmit(0, '立即')">立即提交</el-button>
                <el-button plain type="primary" v-hasPermi="['oce:templateTask:add']" @click="handlePreviewSubmit(1, '异步')">异步提交</el-button>
                <el-button plain type="primary" v-hasPermi="['oce:templateTask:add']" @click="handlePreviewSubmit(2, '定时')">定时提交</el-button>
              </div>
            </div>
          </div>
        </el-row>
        <div class="flex flex-row">
          <template v-for="(item, index) in advertiserArray" :key="item">
            <el-tooltip :content="item.name" placement="top">
              <div class="adv-name" :class="{ 'active': index == activeIndex }" @click="handleSelectData(item, index)">
                <div>{{ item.name }}</div>
              </div>
            </el-tooltip>
          </template>
        </div>
      </template>
      <div class="flex items-center justify-end text-[12px] pb-[15px]">
        <div class="mr-[16px]">
          项目数量：<span class="font-bold">{{ selectData.length }}</span>
        </div>
        <div class="mr-[16px]">
          广告数量：<span class="font-bold">{{ advCount }}</span>
        </div>
        <!-- <div class="mr-[16px]">已有项目：<span class="font-bold">10/200</span></div>
        <div class="mr-[16px]">当日新建广告数：<span class="font-bold">20/500</span></div>
        <div class="mr-[16px]">
          所有广告配额：<span class="font-bold"><span class="text-[#FF4D4F]">20</span>/50</span>
        </div> -->
      </div>
      <el-table :data="selectData" v-loading="loading" style="width: 100%"
        ><!--:span-method="objectSpanMethod"-->
        <el-table-column class-name="first-header">
          <el-table-column label="项目" align="center" style="background: #fff" width="600" class-name="advertising">
            <template #default="scope">
              <div class="sub-table-header" v-if="scope.$index === 0">
                <div class="flex header-row">
                  <div class="header-cell w-[300px]">项目信息</div>
                  <div class="header-cell w-[300px]">转化目标</div>
                </div>
              </div>
              <div class="flex h-full sub-table-body">
                <div class="text-[12px] w-[300px] h-full text-left ml-10">
                  <div>项目名称: {{ scope.row?.name }}</div>
                  <div>项目状态: {{ scope.row?.operation === 'ENABLE' ? '开启' : '关闭' }}</div>
                  <div>推广目的: {{ scope.row?.landingType === 'MICRO_GAME' ? '小程序' : '-' }}</div>
                  <div>营销场景: {{ scope.row?.marketingGoal === 'VIDEO_AND_IMAGE' ? '短视频/图片' : '直播' }}</div>
                  <div>广告类型: {{ scope.row?.adType === 'ALL' ? '通投广告' : '-' }}</div>
                  <div>投放模式: {{ scope.row?.deliveryMode === 'MANUAL' ? '手动投放' : '自动投放' }}</div>
                </div>
                <div class="text-[12px] w-[300px] text-left ml-10">
                  <div>优化目标: {{ scope.row?.optimizeGoal?.externalAction == 'TYPE_ACTIVE' ? '激活' : '广告变现ROI' }}</div>
                  <div>关联产品: {{ scope.row?.relatedProduct === 'SINGLE' ? '启用' : '不启用' }}</div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="广告" align="center" class-name="advertising">
            <template #default="scope">
              <!-- 显示子列表的表头 -->
              <div class="sub-table-header" v-if="scope.$index === 0">
                <div class="flex header-row">
                  <div class="header-cell w-[300px]">广告名称</div>
                  <div class="header-cell w-[150px]">创意素材</div>
                  <div class="header-cell w-[250px]">标题包</div>
                  <div class="flex-1 header-cell">落地页</div>
                </div>
              </div>
              <!-- 显示子列表内容 -->
              <div class="sub-table-body">
                <div v-for="(promo, index) in scope.row.promotionList" :key="index" class="flex sub-table-row">
                  <div class="sub-table-cell w-[300px]">{{ promo.name }}</div>
                  <div class="sub-table-cell w-[150px]" @click="handleClick(promo)">
                    已选：
                    {{ promo.promotionMaterials.videoMaterialList?.length }}
                    个
                  </div>
                  <div class="sub-table-cell w-[250px]">
                    <span class="text-[12px]" v-if="promo.titleWrapName">
                      {{ promo.titleWrapName }}
                    </span>
                    <span v-else class="text-[12px]">-</span>
                  </div>
                  <div class="flex-1 sub-table-cell">
                    <template v-if="promo.promotionMaterials.playletSeriesUrlList?.length">
                      <div v-for="(item, idx) in promo.promotionMaterials.playletSeriesUrlList" :key="idx" class="text-[12px]">
                        {{ item }}
                      </div>
                    </template>
                    <template v-if="promo.promotionMaterials.externalUrlMaterialList?.length">
                      <div v-for="(item, idx) in promo.promotionMaterials.externalUrlMaterialList" :key="idx" class="text-[12px]">
                        {{ item }}
                      </div>
                    </template>
                    <span v-else class="text-[12px]">-</span>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- copy过来的 -->
    <el-dialog title="预览" v-model="dialogImgVisible" append-to-body :close-on-click-modal="true" v-if="false">
      <img
        :src="selectRowData.videoMaterialList[0]?.posterUrl"
        :key="item.name"
        style="max-width: 100%; max-height: 70vh; display: block; margin: 0 auto"
        alt=""
        v-if="selectRowData?.fileType == 'image'"
      />
      <video
        :src="selectRowData.videoMaterialList[0]?.posterUrl"
        controls="controls"
        style="max-width: 100%; max-height: 70vh; display: block; margin: 0 auto"
      ></video>
      <template #footer>
        <div class="material-footer">
          <el-button type="primary" @click="dialogImgVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="定时提交" v-model="dialogSubmit.visible" width="500px" append-to-body :close-on-click-modal="true">
      <el-form>
        <el-form-item v-if="dialogSubmit.type == 2" label="定时发布时间">
          <el-date-picker
            v-model="dialogSubmit.pushTime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetime"
            placeholder="选择日期时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="material-footer">
          <el-button type="primary" @click="dialogSubmit.visible = false">取消</el-button>
          <el-button type="primary" @click="viewSubmit">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type { TableColumnCtx } from 'element-plus';
import { h, ref } from 'vue';
import { debounce, union } from 'lodash';
import { Request } from '@/api/project/types';
import { useAppStore } from '@/store/modules/app';
const appStore = useAppStore();
import { addTemplateTask } from '@/api/project';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

interface SpanMethodProps {
  row: Request;
  column: TableColumnCtx<Request>;
  rowIndex: number;
  columnIndex: number;
}

const props = defineProps<{
  paramsData: object;
  showAdvPreview: boolean;
  tableData: Request[];
  addProjectInfo: Request;
  advertiserArray: {
    id: number;
    name: string;
  }[];
}>();

const tableData = ref<Request[]>([]);
const dialogImgVisible = ref(false);
const dialogSubmit = reactive({
  visible: false,
  type: 1,
  pushTime: null
});
const loading = ref(true);
const selectRowData = ref();
const selectData = ref([]);
const advCount = ref(0); // 广告数量
const activeIndex = ref(0); // 当前选中的广告主

// 点击素材
const handleClick = (row: Request) => {
  selectRowData.value = row.groupQos;
  dialogImgVisible.value = true;
};

const handleChange = (val: string) => {
  console.log(val, 'val');
};
// 选中数据处理
const handleSelectData = async (val: any, idx) => {
  advCount.value = 0;
  selectData.value = [];
  props.tableData.forEach((item) => {
    if (item.advertiserId == val.id) {
      selectData.value = item.projectList;
    }
  });
  selectData.value.forEach((item) => {
    advCount.value += item.promotionList.length;
  });
  activeIndex.value = idx;
  console.log(selectData.value, 'selectData.value');
};

// 合并逻辑
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }: SpanMethodProps) => {
  // if (columnIndex < 3) {
  //   const rowspan = advCount.value / props.addProjectInfo?.projectNum;
  //   return rowIndex % rowspan === 0 ? { rowspan, colspan: 1 } : { rowspan: 0, colspan: 0 };
  // }
  // return { rowspan: 1, colspan: 1 };
};

// 组合表格数据
const initData = async () => {
  tableData.value = props.tableData;
  tableData.value.map((item) => {
    props.advertiserArray.map((advertiser, index) => {
      if (item.advertiserId == advertiser.id) {
        item.advertiserName = advertiser.name;
      }
    });
  });
  await handleSelectData(props.advertiserArray[0], 0);
};
// 预览提交
const viewSubmit = debounce(async () => {
  if (dialogSubmit.type == 2 && !dialogSubmit.pushTime) {
    ElMessage({
      type: 'error',
      message: '请选择定时发布时间'
    });
    proxy?.$modal.closeLoading();
    return;
  }
  try {
    addTemplateTask({
      accountId: appStore.accountId,
      projectJson: JSON.stringify(props.paramsData),
      projectPromotionList: props.tableData,
      submitType: dialogSubmit.type,
      pushTime: dialogSubmit.type == 2 ? dialogSubmit.pushTime : null
    })
      .then((res) => {
        ElMessage({
          type: 'success',
          message: '提交成功'
        });
        dialogSubmit.visible = false;
        proxy?.$modal.closeLoading();
      })
      .catch((err) => {
        proxy?.$modal.closeLoading();
      });
  } finally {
    // proxy?.$modal.closeLoading();
  }
}, 300);
const handlePreviewSubmit = (type, text) => {
  dialogSubmit.type = type;
  if (type != 2) {
    ElMessageBox.confirm('确定' + text + '提交?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        proxy?.$modal.loading('正在提交，请稍后...');
        viewSubmit();
      })
      .catch(() => {
        proxy?.$modal.closeLoading();
      });
  } else {
    dialogSubmit.visible = true;
  }
};

watch(
  () => props.showAdvPreview,
  () => {
    selectData.value = [];
    initData();
    console.log(selectData.value, 'selectData.value22');
  }
);
onMounted(() => {
  initData();
  setTimeout(() => {
    loading.value = false;
  }, 500);
});
</script>

<style lang="scss" scoped>
.header-cell {
  border-right: 1px solid var(--el-table-border-color);
  border-bottom: 1px solid var(--el-table-border-color);
  background: #f8f8f9;
  font-weight: 600;
}
.header-cell:last-child {
  border-right: none;
}
.sub-table-body {
  .sub-table-row {
    border-bottom: 1px solid var(--el-table-border-color);
  }
}
::v-deep(.projectCont) {
  padding-left: 0 !important;
  padding-right: 0 !important;
}
::v-deep(.el-card__header) {
  padding: 14px 15px 0px !important;
}
::v-deep(.first-header) {
  display: none;
}

.adv-name {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #000;
  background-color: #e8f3ff;
  border-top: 1px solid #ccc;
  border-right: 1px solid #ccc;
  border-left: 1px solid #ccc;
  min-width: 200px;
  max-width: 400px;
  font-size: 14px;
  overflow: hidden;
  padding: 0 12px;
  position: relative;
  box-sizing: border-box;
  height: 40px;
  margin-right: 2px;
  margin-left: 2px;
  cursor: pointer;
  border-top-left-radius: 6px;
  border-top-right-radius: 6px;
  div {
    width: 100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
.adv-name.active {
  color: #197afb;
  background-color: #e8f3ff;
  border-top: 1px solid #197afb;
  border-right: 1px solid #197afb;
  border-left: 1px solid #197afb;
}
.content {
  .items {
    border-right: 0px;
  }
  .material-list {
    padding: 0 20px;
    box-sizing: border-box;
    .material-item {
      overflow-y: scroll;
      flex-wrap: nowrap;
    }
    img {
      width: 50px;
      height: 80px;
      margin: 0 5px;
    }
  }
  .header-pack,
  .landing-page {
    .header-pack-box,
    .landing-page-box {
      .header-pack-name,
      .landing-page-name {
        width: 100%;
        height: 30px;
        line-height: 30px;
        margin: 0 15px;
        background-color: #f5f5f5;
        padding: 0 5px;
        box-sizing: border-box;
        border-radius: 10px;
      }
    }
  }
}
.titbox {
  border-bottom: 1px solid #f1f1f1;
}
:deep(.advertising) {
  padding: 0 !important;
  .cell {
    padding: 0 !important;
  }
}
/* 方法1：全局修改所有表格单元格 */
:deep(.el-table td.el-table__cell) {
  vertical-align: top; /* 顶部对齐 */
}

/* 方法2：只修改特定列的单元格 */
:deep(.el-table .custom-column .el-table__cell) {
  vertical-align: top;
}
</style>
